package com.sky.aspect;

import com.sky.annotation.AutoFill;
import com.sky.context.BaseContext;
import com.sky.enumeration.OperationType;
import lombok.extern.slf4j.Slf4j;
import org.aopalliance.intercept.Joinpoint;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MemberSignature;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.time.LocalDateTime;

/**
 * 实现公共字段自动填充处理逻辑
 */
// 默认实体参数为单个实体
// 暂不支持实体参数为集合的方法进行自动填充
@Component
@Aspect
@Slf4j
public class AutoFillAspect {

    @Pointcut("execution(* com.sky.mapper.*.*(..)) && @annotation(com.sky.annotation.AutoFill)")
    public void autoFillPointcut(){
    }

    @Before("autoFillPointcut()")
    public void autoFill(JoinPoint joinpoint) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        log.info("开始进行公共字段填充");

        //获取被拦截方法的操作类型
        MethodSignature signature = (MethodSignature) joinpoint.getSignature();
        AutoFill autoFill = signature.getMethod().getAnnotation(AutoFill.class);
        OperationType type = autoFill.value();

        //获得实体对象，默认参数列表第一位
        Object[] args = joinpoint.getArgs();
        if(args==null || args.length==0){
            return;
        }
        //默认为单个实体，不是实体集合形式
        Object entity = args[0];

        //准备填充数据
        LocalDateTime now = LocalDateTime.now();
        Long currentId = BaseContext.getCurrentId();

        //根据操作类型为属性赋值
        if(type==OperationType.INSERT){
            Class<?> c = entity.getClass();
            Method setCreateTime = c.getDeclaredMethod("setCreateTime", LocalDateTime.class);
            Method setUpdateTime = c.getDeclaredMethod("setUpdateTime", LocalDateTime.class);
            Method setCreateUser = c.getDeclaredMethod("setCreateUser", Long.class);
            Method setUpdateUser = c.getDeclaredMethod("setUpdateUser", Long.class);
            setCreateTime.invoke(entity,now);
            setUpdateTime.invoke(entity,now);
            setCreateUser.invoke(entity,currentId);
            setUpdateUser.invoke(entity,currentId);
        }else if(type==OperationType.UPDATE){
            Class<?> c = entity.getClass();
            Method setUpdateTime = c.getDeclaredMethod("setUpdateTime", LocalDateTime.class);
            Method setUpdateUser = c.getDeclaredMethod("setUpdateUser", Long.class);
            setUpdateTime.invoke(entity,now);
            setUpdateUser.invoke(entity,currentId);
        }

    }
}
